package com.liuweiheng.cloud.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * 实现线程方法：实现Callable接口，且有返回值
 * @author lwh
 * @since 2021/5/10
 */
public class MyCallable implements Callable<String> {

    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
    /**
     * 核心线程数、最大线程数、存活时间，时间单位，存放提交但未执行任务的队列，创建线程的工厂类，等待队列满后的策略
     */
    private static ExecutorService taskExe = new ThreadPoolExecutor(10,20,200L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),namedThreadFactory);

    @Override
    public String call() throws Exception {
        System.out.println("线程" + Thread.currentThread().getName() + "启动");
        return Thread.currentThread().getName();
    }

    public static void main(String[] args) throws Exception{

        Future<String> future = taskExe.submit(new MyCallable());

        // future.get()会一直阻塞线程
        System.out.println("线程返回值：" + future.get());


        FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
        taskExe.submit(futureTask);
        System.out.println(futureTask.get());

        Thread.sleep(2000);

        // 结束线程
        System.out.println("线程池关闭");
        taskExe.shutdown();


    }
}
